//
//  SegmentView.m
//  时光影院
//
//  Created by 贝沃it on 15/6/30.
//  Copyright © 2015年 贝沃it. All rights reserved.
//

#import "SegmentView.h"

@implementation SegmentView

- (id)initWithFrame:(CGRect)frame withTitles:(NSArray *)titles segmentBlock:(SegmentBlock)segmentBlock {

    if (self = [super initWithFrame:frame]) {
        
        self.titles = titles;
        
        _segmentBlock = segmentBlock;
    }
    
    return self;
    
}

//按钮标题的set方法
-(void)setTitles:(NSArray *)titles{

    _titles = titles;
    
    //根据count值创建对应数目的按钮
    _itemCount = (int)titles.count;
    for (int i = 0; i < _itemCount; i++) {

        if ([_titles[i] isEqualToString:@""]) {
            
            continue;//跳出当前循环
        }
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.backgroundColor = [UIColor colorWithRed:150 green:12 blue:14 alpha:1];//为什么不可以？？？？？？？
        btn.backgroundColor = [UIColor grayColor];
        [btn setFrame:CGRectMake(i*self.frame.size.width/_itemCount, 0, self.frame.size.width/_itemCount, self.frame.size.height)];
        [btn setTitle:_titles[i] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        btn.tag = 100+i;
        
        [btn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
        
        if (i == 0) {
            btn.selected = YES;
        }
        
        [self addSubview:btn];
    }
    
    _selectedImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-2, self.frame.size.width/_itemCount, 2)];
    
    _selectedImageV.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:_selectedImageV];
}

- (void)setSelectedImage:(NSString *)selectedImage {
    
    _selectedImageV.image = [UIImage imageNamed:selectedImage];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {

    UIButton *btn = (UIButton *)[self viewWithTag:100+selectedIndex];
    
    [self buttonAction:btn];

}

-(void)buttonAction:(UIButton *)sender{

    for (UIView *view in self.subviews) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *btn = (UIButton *)view;
            btn.selected = NO;
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
        }
        
    }
    
    sender.selected = YES;
    sender.titleLabel.font = [UIFont systemFontOfSize:15];
    
    int index = (int)sender.tag - 100;
    
    CGFloat width = self.frame.size.width/_titles.count;
    
    [UIView animateWithDuration:.2 animations:^{

        _selectedImageV.frame = CGRectMake(index * width, self.frame.size.height-2, width, 2);
    }];
    
    if (_segmentBlock) {
    
        _segmentBlock(index);
    }
    
}

@end
